package uu.tools.edge;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class TextSimilarityCalculator {

    // 清洗文本, 只保留有效信息, 文字
    private static String cleanText(String str) {
        char[] chars = str.toCharArray();
        char[] filterChars = new char[chars.length];
        int filterCharsIndex = 0;
        for (char aChar : chars) {
            if ((aChar >= '一' && aChar <= '龥') ||
                    (aChar >= 'a' && aChar <= 'z') ||
                    (aChar >= 'A' && aChar <= 'Z') ||
                    (aChar >= '0' && aChar <= '9')) {
                filterChars[filterCharsIndex++] = aChar;
            }
        }
        return new String(Arrays.copyOf(filterChars, filterCharsIndex));
    }

    public static double contains(String reference, String str) {
        reference = cleanText(reference);
        if (reference.length() == 2) {
            return 0f;
        }
        str = cleanText(str);

        List<String> referenceList = new LinkedList<>();
        List<String> strList = new LinkedList<>();
        for (int i = 0; i < reference.length() - 2; i++) {
            referenceList.add(reference.substring(i, i + 3));
        }
        for (int i = 0; i < str.length() - 2; i++) {
            strList.add(str.substring(i, i + 3));
        }

        int ppn = 0;    // 吻合次数
        int lastIndex = 0;
        for (String s : referenceList) {
            for (int i = 0; i < strList.size(); i++) {
                if (strList.get(i).equals(s)) {
                    strList.remove(i);
                    if (!(ppn != 0 && i > lastIndex + 6)) { // 滑动对比, 下次滑动吻合很上次距离过大, 本次匹配算无效
                        ppn++;
                        lastIndex = i;
                    }
                    break;
                }
            }
        }
        return (double) ppn / (reference.length() - 2);
    }

    public static double similarity(String reference, String str) {
        reference = cleanText(reference);
        str = cleanText(str);

        List<String> referenceList = new LinkedList<>();
        List<String> strList = new LinkedList<>();
        for (int i = 0; i < reference.length() - 2; i++) {
            referenceList.add(reference.substring(i, i + 3));
        }
        for (int i = 0; i < str.length() - 2; i++) {
            strList.add(str.substring(i, i + 3));
        }

        int ppn = 0;    // 吻合次数
        for (String s : referenceList) {
            for (int i = 0; i < strList.size(); i++) {
                if (strList.get(i).equals(s)) {
                    ppn++;
                    strList.remove(i);
                    break;
                }
            }
        }
        return (double) ppn / reference.length();
    }
}
